package cn.smart.epic.modular.system.controller;

import cn.smart.epic.common.annotion.Permission;
import cn.smart.epic.common.annotion.log.BussinessLog;
import cn.smart.epic.common.constant.Const;
import cn.smart.epic.common.constant.Dict;
import cn.smart.epic.common.controller.BaseController;
import cn.smart.epic.common.exception.BizExceptionEnum;
import cn.smart.epic.common.exception.BussinessException;
import cn.smart.epic.common.node.VTreeNode;
import cn.smart.epic.common.page.PageReq;
import cn.smart.epic.common.persistence.dao.RoleMapper;
import cn.smart.epic.common.persistence.dao.UserMapper;
import cn.smart.epic.common.persistence.model.Role;
import cn.smart.epic.common.persistence.model.User;
import cn.smart.epic.core.log.LogObjectHolder;
import cn.smart.epic.core.support.HttpKit;
import cn.smart.epic.core.util.CommonUtil;
import cn.smart.epic.core.util.Convert;
import cn.smart.epic.core.util.ToolUtil;
import cn.smart.epic.modular.system.service.IRoleService;
import cn.smart.epic.modular.system.warpper.RoleWarpper;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @Auther Uncle_Z
 * @date 2018/8/7 10:05
 * @Email:2545375@qq.com
 * @Descrition
 * @since 1.0
 */

@Api(value = "/role",tags = "角色管理")
@RestController
@RequestMapping(value = "/role/")
public class RoleController extends BaseController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private IRoleService roleService;

    @GetMapping("list")
    @Permission()
    public JSONObject list(String roleName){
        PageReq pageReq = defaultPage();
        Page page = PageHelper.startPage(pageReq.getOffset(),pageReq.getLimit());
        List<JSONObject> roleList = roleMapper.selectRoles(roleName);
        return CommonUtil.successPage(((List<JSONObject>) new RoleWarpper(roleList).warp()),page.getTotal());
    }

    @PostMapping("add")
    @Permission(Const.ADMIN_NAME)
    @BussinessLog(name = "添加角色",key="name",dict = Dict.RoleDict)
    public JSONObject add(@RequestBody @Valid Role role, BindingResult result) {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        role.setId(null);
        roleMapper.insert(role);
        return CommonUtil.successJson();
    }

    @PutMapping("edit")
    @Permission(Const.ADMIN_NAME)
    @BussinessLog(name = "修改角色",key="name",dict=Dict.RoleDict)
    public JSONObject edit(@RequestBody @Valid Role role,BindingResult result){
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Role oldRole = roleMapper.selectByPrimaryKey(role.getId());
        LogObjectHolder.me().set(oldRole);

        roleMapper.updateByPrimaryKeySelective(role);
        return CommonUtil.successJson();
    }

    @DeleteMapping("remove/{roleId}")
    @BussinessLog(name = "删除角色",key = "roleId",dict = Dict.RoleDict)
    @Permission(Const.ADMIN_NAME)
    public JSONObject remove(@PathVariable Integer roleId){
        if (ToolUtil.isEmpty(roleId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }

        if (roleId.equals(Const.ADMIN_ID)) {
            throw new BussinessException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }

        roleService.delRoleById(roleId);
        return CommonUtil.successJson();
    }

    @GetMapping("allRole")
    public JSONObject findAllRole(){
        List<Role> roleList = roleMapper.selectAll();
        JSONObject json = new JSONObject();
        json.put("returnCode", Const.SUCCESS_CODE);
        json.put("returnMsg", Const.SUCCESS_MSG);
        json.put("returnData",roleList);
        return json;
    }


    @GetMapping(value = "roleTreeListByUserId/{userId}")
    public JSONObject roleTreeListByUserId(@PathVariable Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        String roleId = user.getRoleid();
        if (ToolUtil.isEmpty(roleId)) {
            List<VTreeNode> roleTreeList = roleMapper.selectRoleTree();
            return CommonUtil.successJson(roleTreeList);
        }else{
            String[] strArray = Convert.toStrArray(",",roleId);
            List<VTreeNode> roleTreeListByUserId = roleMapper.roleTreeListByRoleId(strArray);
            return CommonUtil.successJson(roleTreeListByUserId);
        }
    }

    @PostMapping("setAuthority")
    @BussinessLog(name = "配置权限", key = "roleId,ids", dict = Dict.RoleDict)
    @Permission(Const.ADMIN_NAME)
    public JSONObject setAuthority(){
        Map<String,String> params = HttpKit.getRequestParameters();
        Integer roleId = Integer.parseInt(params.get("roleId"));
        if (ToolUtil.isEmpty(roleId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        roleService.setAuthority(roleId,params.get("ids"));
        return CommonUtil.successJson();
    }
}
